var fs = require('fs');
var readline = require('readline');

var lines = []
var ds = readline.createInterface({
  input: fs.createReadStream('UWBdata.js')
})
ds.on('line', function (line) {
  var seperator = line.indexOf(":");
  var name = line.slice(0, seperator);
  var value = JSON.parse(line.slice(seperator + 1));
  // myEmitter.emit(name, value);
  lines.push({name: name, value: value})
});
var name = [];
ds.on('close', function () {
  for (var i = 0; i < lines.length; i++) {
    var fileName = "_" + lines[i].value.nodeID + "." + lines[i].name;
    if (lines[i].value.nodeId && name.indexOf("_" + lines[i].value.nodeId + "." + lines[i].name) === -1) {
      name.push("_" + lines[i].value.nodeId + "." + lines[i].name)
    }
    if (lines[i].name !== "user_stat" && name.indexOf(fileName) === -1) {
      name.push(fileName)
    }
  }

  fileWhite();
});

function fileWhite() {
  for (var i = 0; i < name.length; i++) {
    white(i)
  }
}

function white(i) {
  fs.open(name[i], 'a', function (err, fd) {
    if (err) {
      return console.error(err);
    }
    for (var j = 0; j < lines.length; j++) {
      if (name[i].indexOf(lines[j].name) !== -1) {
        fs.writeFile(fd, JSON.stringify(lines[j].value) + "\n", function (err) {
        })
      }
    }
    console.log("文件打开成功！");
  });
}

